#include <iostream>
#include <cstdio>
#include "Map.hpp"


int main(int argc, char* argv[])
{
  if (argc != 5) {
    std::cout << "Syntax: import_map <map_file> <art_file> <palette_file> <output_file>" << std::endl;
    return 1;
  }


  FILE* map_file = fopen(argv[1], "rb");
  if (map_file == NULL) {
    std::cout << "Could not open map file" << std::endl;
    return 1;
  }

  FILE* art_file = fopen(argv[2], "rb");
  if (art_file == NULL) {
    fclose(map_file);
    std::cout << "Could not open art file" << std::endl;
    return 1;
  }

  FILE* palette_file = fopen(argv[3], "rb");
  if (palette_file == NULL) {
    fclose(map_file);
    fclose(art_file);
    std::cout << "Could not open palette file" << std::endl;
    return 1;
  }


  sMap map(100, 100);
  sTileset& tileset = map.GetTileset();
  tileset.Create(128);
  tileset.SetTileSize(20, 20);
  
  // read the map
  sLayer& layer = map.GetLayer(0);
  for (int i = 0; i < 100 * 100; i++) {
    layer.SetTile(i % 100, i / 100, fgetc(map_file));
  }

  // read palette
  RGB palette[256];
  fread(palette, 3, 256, palette_file);

  RGBA palette_rgba[256];
  for (int i = 0; i < 256; i++) {
    palette_rgba[i].red   = palette[i].red   * 4;
    palette_rgba[i].green = palette[i].green * 4;
    palette_rgba[i].blue  = palette[i].blue  * 4;
    palette_rgba[i].alpha = (i != 0) * 255;
  }


  // read the tileset
  for (int i = 0; i < 128; i++) {
    for (int y = 0; y < 20; y++) {
      for (int x = 0; x < 20; x++) {
        byte color = fgetc(art_file);
        CImage32& image = tileset.GetTile(i);
        image.GetPixels()[y * image.GetWidth() + x] = palette_rgba[color];
      }
    }
  }

  
  // attempt to save the output map
  if (map.Save(argv[4])) {
    std::cout << "save succeeded" << std::endl;
  } else {
    std::cout << "save failed" << std::endl;
  }


  fclose(map_file);
  fclose(art_file);
  fclose(palette_file);

  return 0;
}
